package com.example.base;

import android.app.Application;
import android.content.Context;

import java.util.Enumeration;
import java.util.HashMap;

import dalvik.system.DexFile;
import dalvik.system.PathClassLoader;

public class BaseApp extends Application {

    public static HashMap<String, Class> skillMap = new HashMap<>();

    @Override
    public void onCreate() {
        super.onCreate();
        loadSkills();
    }


    private void loadSkills() {
        scan(this, "com.example.app.skills");
    }

    public static void scan(Context ctx, String entityPackage) {
        long last = System.currentTimeMillis();
        System.out.println("Load class scanning");
        try {
            PathClassLoader classLoader = (PathClassLoader) Thread
                    .currentThread().getContextClassLoader();
            DexFile dex = new DexFile(ctx.getPackageResourcePath());
            Enumeration<String> entries = dex.entries();
            while (entries.hasMoreElements()) {
                String entryName = entries.nextElement();
                if (entryName.startsWith(entityPackage)) {
                    Class<?> entryClass = Class.forName(entryName, true, classLoader);//疑问：Class.forName(entryName);这种方式不知道为什么返回null，哪位大神知道原因，请指点一下小弟吧  感激不尽
                    System.out.println("Load class: " + entryClass.getCanonicalName());
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println("Load class scanning time " + (System.currentTimeMillis() - last));
    }

    public static void addSkill(String intent, Class skillManager) {
        skillMap.put(intent, skillManager);
    }
}
